import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:chatgreat/helper/logger.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:circular_countdown_timer/circular_countdown_timer.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_speech/flutter_speech.dart';
import 'package:go_router/go_router.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../../bloc/chat_message_bloc.dart';
import '../../helper/color.dart';
import '../../helper/helper.dart';
import '../../helper/my_widget.dart';
import '../../repo/api_server.dart';
import '../../repo/model/message.dart';
import '../component/audio_player.dart';
import '../creative_island/draw/draw_result.dart';

enum SpeehStatus {
  listing,
  ponder,
  speek,
}

class HomeSpeehChatPage extends StatefulWidget {
  final SettingRepository setting;
  final int roomId;
  final String name;
  final String? avater;

  const HomeSpeehChatPage({
    super.key,
    required this.setting,
    required this.roomId,
    required this.name,
    this.avater,
  });

  @override
  State<HomeSpeehChatPage> createState() => _HomeSpeehChatPageState();
}

class _HomeSpeehChatPageState extends State<HomeSpeehChatPage> {
  late SpeechRecognition _speech;
  late AudioPlayerController _audioPlayerController;

  // 显示音频播放器的状态
  bool showAudioPlayer = false;

  // 监听内容
  var listenContent = '';
  bool _speechRecognitionAvailable = false;
  bool _isListening = false;
  SpeehStatus _speehStatus = SpeehStatus.listing;
  CountDownController controller = CountDownController();

  @override
  void initState() {
    _speech = SpeechRecognition();
    _audioPlayerController = AudioPlayerController(useRemoteAPI: true);

    _audioPlayerController.onPlayStopped = () {
      showAudioPlayer = false;
      listenContent = '';
      _speehStatus = SpeehStatus.listing;
      if (mounted) {
        setState(() {});
      }
    };
    _audioPlayerController.onPlayAudioStarted = () {
      setState(() {
        showAudioPlayer = true;
        _speehStatus = SpeehStatus.speek;
      });
    };
    _audioPlayerController.onPlayCompletion = () {
      listenContent = '';
      showAudioPlayer = false;
      _speehStatus = SpeehStatus.listing;
      if (mounted) {
        setState(() {});
      }

      // 重新开始监听
      startRecognition();
    };
    _audioPlayerController.onPlayAudioLoading = (loading) {
      if (showAudioPlayer) {
        if (loading) {
          _speehStatus = SpeehStatus.ponder;
        } else {
          _speehStatus = SpeehStatus.speek;
        }
      }
      if (mounted) {
        setState(() {});
      }
    };
    super.initState();
    // go. /room/$id/chat'
    // context.read<ChatMessageBloc>().add(ChatMessageGetRecentEvent());

    Future.delayed(const Duration(milliseconds: 400)).then((value) {
      startRecordInputDialog();
    });
  }

  @override
  void dispose() {
    if (_speehStatus == SpeehStatus.listing) {
      cancel();
      stop();
    } else if (_speehStatus == SpeehStatus.ponder ||
        _speehStatus == SpeehStatus.speek) {
      _audioPlayerController.stop();
    }
    _audioPlayerController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;

    // listenContent = '我觉得估唔到哦爱的会哦玩i回答我i很大哦i啊好哇对哦挖好滴我好ID哈偶单号问哈对哦阿嘎温度啊给我杜伽哇对哦挖好滴我好ID哈偶单号问哈对哦阿嘎温度啊给我杜伽哇对哦挖好滴我好ID哈偶单号问哈对哦阿嘎温度啊给我杜伽哇对哦挖好滴我好ID哈偶单号问哈对哦阿嘎温度啊给我杜伽哇对哦挖好滴我好ID哈偶单号问哈对哦阿嘎温度啊给我杜伽哇对哦挖好滴我好ID哈偶单号问哈对哦阿嘎温度啊给我杜伽哇对哦挖好滴我好ID哈偶单号问哈对哦阿嘎温度啊给我杜伽哇对哦挖好滴我好ID哈偶单号问哈对哦阿嘎温度啊给我杜伽';
    // listenContent = '我觉得估唔到哦爱的会哦玩i回答我i很大哦i啊好哇对哦挖';

    return BackgroundContainer(
      setting: widget.setting,
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.transparent,
          image: DecorationImage(
            image: AssetImage('images/bg1.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            centerTitle: true,
            elevation: 0,
            backgroundColor: Colors.transparent,
            title:
                MyTextWeight(widget.name, 18, Colors.white, FontWeight.normal),
            leading: IconButton(
              padding: const EdgeInsets.all(16),
              icon: const Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              onPressed: () {
                if (context.canPop()) {
                  context.pop();
                }
              },
            ),
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox(height: 60),
              ClipRRect(
                  borderRadius: BorderRadius.circular(60),
                  child: isNotBlank(widget.avater ?? '')
                      ? CachedNetworkImage(
                          width: 120,
                          height: 120,
                          imageUrl: widget.avater!,
                          fit: BoxFit.cover,
                        )
                      : imgWidget(80, 80, 'AI_avater')),
              const SizedBox(height: 20),
              Expanded(
                child: Center(
                  child: ListView(
                    shrinkWrap: true,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(left: 16, right: 16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            if (listenContent.isNotEmpty)
                              Container(
                                margin: const EdgeInsets.only(right: 10),
                                child: CountDownProgressBar(
                                  duration: 9,
                                  width: 24,
                                  height: 24,
                                  strokeWidth: 4,
                                  fontSize: 15,
                                  initialDuration: 0,
                                  controller: controller,
                                  onComplete: (controller) {
                                    print('------------------> ${controller.isPaused}, ${controller.isRestarted}, ${controller.isResumed}, ${controller.isStarted}');
                                    if (controller.isPaused) {
                                      return;
                                    }
                                    Logger.instance.i('--------------------------> 8秒倒计时完毕');
                                    // 规定8秒停止监听
                                    stop();
                                    // Future.delayed(const Duration(milliseconds: 100)).then((value) => onRecognitionComplete(listenContent));
                                  },
                                ),
                              ),
                            MyTextWeight(_getStatusTitle(), 17, Colors.white,
                                FontWeight.normal),
                            AnimatedTextKit(
                              repeatForever: true,
                              animatedTexts: [
                                TypewriterAnimatedText('...',
                                    speed: const Duration(milliseconds: 50),
                                    textStyle: const TextStyle(
                                      color: Colors.white,
                                      fontSize: 17,
                                    )),
                              ],
                            ),
                          ],
                        ),
                      ),
                      Visibility(
                        visible: _speehStatus == SpeehStatus.listing,
                        maintainAnimation: true,
                        maintainSize: true,
                        maintainState: true,
                        child: Container(
                          alignment: Alignment.center,
                          margin: EdgeInsets.only(
                              left: 34,
                              right: 34,
                              top: listenContent.length > 50 ? 20 : 44),
                          child: MyTextWeight(listenContent, 16,
                              stringToColor('FF18DDEB'), FontWeight.normal),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 20),
              Visibility(
                visible: _speehStatus == SpeehStatus.listing,
                maintainAnimation: true,
                maintainSize: true,
                maintainState: true,
                child: Container(
                  margin:
                      const EdgeInsets.only(left: 10, right: 10, bottom: 35),
                  height: 120.w,
                  width: double.infinity,
                  child: Stack(alignment: Alignment.center, children: [
                    Positioned(
                      top: 0,
                      bottom: 0,
                      left: 0,
                      right: 0,
                      child: ClipRect(
                        child: OverflowBox(
                          child: Image.asset(
                            fit: BoxFit.fitWidth,
                            'assets/record_input.gif',
                          ),
                        ),
                      ),
                    ),
                  ]),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  String _getStatusTitle() {
    if (_speehStatus == SpeehStatus.ponder) {
      return '正在思考';
    } else if (_speehStatus == SpeehStatus.speek) {
      return '我正在讲话，请调大音量收听';
    }
    return '正在收听';
  }

  Future<bool> requestMicrophonePermission() async {
    final status = await Permission.microphone.request();
    return status == PermissionStatus.granted;
  }

  Future<bool> requestSpeechPermission() async {
    final status = await Permission.speech.request();
    return status == PermissionStatus.granted;
  }

  void startRecordInputDialog() async {
    // 麦克风权限
    final microphoneStatus = await Permission.microphone.status;
    if (microphoneStatus != PermissionStatus.granted) {
      // 用户尚未授权，可以尝试请求权限
      bool granted = await requestMicrophonePermission();
      if (!granted) {
        // 用户拒绝了权限请求，可以引导用户到设置页面
        showCupertinoDialog(
            context: context,
            builder: (BuildContext context) {
              return CupertinoAlertDialog(
                title: const Text('提示'),
                content: const Text('你未授权访问麦克风，无法使用语音交流功能，请在设置中允许访问麦克风权限后重试'),
                actions: [
                  CupertinoDialogAction(
                    isDefaultAction: true,
                    child: const Text(
                      '取消',
                      style: TextStyle(
                          color: Colors.white, fontWeight: FontWeight.normal),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  CupertinoDialogAction(
                    isDestructiveAction: true,
                    child: const Text('去设置'),
                    onPressed: () {
                      launchUrlString('App-Prefs:Privacy&path=MICROPHONE');
                    },
                  ),
                ],
                insetAnimationDuration: const Duration(seconds: 2),
              );
            });
        return;
      }
    }

    // 语音识别权限
    final speechStatus = await Permission.speech.status;
    if (speechStatus != PermissionStatus.granted) {
      // 用户尚未授权，可以尝试请求权限
      bool granted = await requestSpeechPermission();
      if (!granted) {
        // 用户拒绝了权限请求，可以引导用户到设置页面
        showCupertinoDialog(
            context: context,
            builder: (BuildContext context) {
              return CupertinoAlertDialog(
                title: const Text('提示'),
                content: const Text('你未授权访问语音识别，无法使用语音交流功能，请在设置中允许访问语音识别权限后重试'),
                actions: [
                  CupertinoDialogAction(
                    isDefaultAction: true,
                    child: const Text(
                      '取消',
                      style: TextStyle(
                          color: Colors.white, fontWeight: FontWeight.normal),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  CupertinoDialogAction(
                    isDestructiveAction: true,
                    child: const Text('去设置'),
                    onPressed: () {
                      launchUrlString(
                          'App-Prefs:Privacy&path=SPEECH_RECOGNITION');
                    },
                  ),
                ],
                insetAnimationDuration: const Duration(seconds: 2),
              );
            });
        return;
      }
    }
    // 语音识别
    setupSpeechRecognition();
  }

  /// 配置识别器
  void setupSpeechRecognition() async {
    _speech.setAvailabilityHandler(onSpeechAvailability);
    _speech.setRecognitionStartedHandler(onRecognitionStarted);
    _speech.setRecognitionResultHandler(onRecognitionResult);
    _speech.setRecognitionCompleteHandler(onRecognitionComplete);
    _speech.setErrorHandler(errorHandler);
    _speechRecognitionAvailable = await _speech.activate('zh_CN');

    if (_speechRecognitionAvailable && !_isListening) {
      activateRecogntion().then((value) => startRecognition());
    }
  }

  //TODO: - record recognition
  Future activateRecogntion() => _speech.activate('zh_CN');

  void startRecognition() => _speech.listen().then((result) {
        print('_MyAppState.start => result $result');
        if (result) {
          _speehStatus = SpeehStatus.listing;
        }
        setState(() {
          _isListening = result;
        });
      });

  void cancel() => _speech.cancel().then((_) {
        print('_MyAppState.onRecognitionCancel... ');
        _speehStatus = SpeehStatus.listing;
        if (mounted) {
          setState(() => _isListening = false);
        }
      });

  void stop() => _speech.stop().then((_) {
        print('_MyAppState.onRecognitionStop... ');
        _speehStatus = SpeehStatus.listing;
        if (mounted) {
          setState(() => _isListening = false);
        }
      });

  void onSpeechAvailability(bool result) =>
      setState(() => _speechRecognitionAvailable = result);

  void onRecognitionStarted() {
    print('_MyAppState.onRecognitionStarted...');
    _speehStatus = SpeehStatus.listing;
    _isListening = true;
  }

  void onRecognitionResult(String text) {
    print('_MyAppState.onRecognitionResult... $text');

    setState(() => listenContent = text);
  }

  void onRecognitionComplete(String text) {
    print('_MyAppState.onRecognitionComplete... $text');

    if (controller.isStarted) {
      controller.pause();
    }
    if (isNotBlank(listenContent)) {
      // 记录聊天记录
      context.read<ChatMessageBloc>().add(
          ChatMessageSaveEvent(
              Message(
                Role.sender,
                listenContent,
                user: 'me',
                ts: DateTime.now(),
                type: MessageType.text,
                roomId: widget.roomId,
                userId: APIServer().localUserID(),
                like: 0,
                collection: 0,
              )
          ));

      _audioPlayerController.playAudio(listenContent, widget.roomId).then((value) {
        if (value != null && isNotBlank(value.content)) {
          context.read<ChatMessageBloc>().add(
              ChatMessageSaveEvent(
                Message(
                  Role.receiver,
                  value.content,
                  ts: DateTime.now(),
                  user: 'ai',
                  type: MessageType.text,
                  model: 'chat4o',
                  roomId: widget.roomId,
                  userId: APIServer().localUserID(),
                  serverId: value.id,
                  like: 0,
                  collection: 0,
                )
            )
          );
        }
      });
      listenContent = '';
    }
    if (_speehStatus == SpeehStatus.listing) {
      _speehStatus = SpeehStatus.ponder;
    }
    _isListening = false;
    setState(() {});
  }

  void errorHandler() => setupSpeechRecognition();
}
